package com.aaa.dao;

import com.aaa.entity.Comments;
import com.aaa.entity.Film;
import com.aaa.entity.LeadingUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class CommentsDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    private RowMapper<Comments> rowMapper=new RowMapper<Comments>() {
        public Comments mapRow(ResultSet resultSet, int i) throws SQLException {
            Comments comments=new Comments();
            comments.setId(resultSet.getLong("id"));
            comments.setContent(resultSet.getString("content"));
            comments.setCreate_time(resultSet.getString("create_time"));
            Film film=new Film();
            film.setChinese_name(resultSet.getString("chinese_name"));
            comments.setFilm(film);
            LeadingUser leadingUser=new LeadingUser();
            leadingUser.setLuname(resultSet.getString("luname"));
            comments.setLeadingUser(leadingUser);
            return comments;
        }
    };


    public List<Comments> listPage(String keyword, Integer offset, Integer limit){
        String sql="select c.id,lu.luname,f.chinese_name,c.content,c.create_time,c.fid from comments c  join film f on c.fid =f.id join leading_user lu on c.uid = lu.lid where lu.luname like ? order by c.create_time desc limit ?,?";
        List<Comments> result = jdbcTemplate.query(sql, rowMapper, "%" + keyword + "%", offset, limit);
        return result;
    }


    public Integer count(String keyword){
        String sql="select count(id) as c from comments ";
        List<Integer> count=jdbcTemplate.query(sql, new RowMapper<Integer>() {
            public Integer mapRow(ResultSet resultSet, int i) throws SQLException {
                return resultSet.getInt("c");
            }
        });
        Integer integer=Integer.valueOf(count.get(0).toString());
        return integer;
    }


    public Integer delete(Integer id){
        String sql="delete from comments where id=?";
        int count = jdbcTemplate.update(sql, id);
        return count;
    }
}
